#!/bin/bash

# 图片上传功能测试脚本
echo "🧪 测试图片上传功能..."

# 创建测试图片
echo "📷 创建测试图片..."
convert -size 100x100 xc:blue /tmp/test-upload.jpg 2>/dev/null || {
    echo "创建简单的测试文件..."
    echo "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" | base64 -d > /tmp/test-upload.png
}

# 测试后端直接上传
echo ""
echo "🔧 测试后端直接上传API..."
if [ -f "/tmp/test-upload.jpg" ]; then
    TEST_FILE="/tmp/test-upload.jpg"
elif [ -f "/tmp/test-upload.png" ]; then
    TEST_FILE="/tmp/test-upload.png"
else
    echo "❌ 无法创建测试文件"
    exit 1
fi

# 获取认证token（这里需要替换为实际的token或先登录）
echo "⚠️  注意: 需要有效的认证token才能测试上传"
echo "如果没有token，将显示401错误，这是正常的"

curl -X POST http://localhost:3000/api/upload/image \
     -H "Authorization: Bearer YOUR_TOKEN_HERE" \
     -F "image=@$TEST_FILE" \
     -v

echo ""
echo ""
echo "🌐 测试通过Nginx代理的上传..."
curl -X POST http://localhost/api/upload/image \
     -H "Authorization: Bearer YOUR_TOKEN_HERE" \
     -F "image=@$TEST_FILE" \
     -v

echo ""
echo ""
echo "📋 检查上传目录..."
UPLOAD_DIR="/var/www/web-notes/web-notes-backend/uploads/images"
if [ -d "$UPLOAD_DIR" ]; then
    echo "✅ 上传目录存在: $UPLOAD_DIR"
    echo "目录权限: $(ls -ld $UPLOAD_DIR)"
    echo "目录内容: $(ls -la $UPLOAD_DIR | wc -l) 个文件"
    if [ "$(ls -la $UPLOAD_DIR | wc -l)" -gt 3 ]; then
        echo "最近的文件:"
        ls -la $UPLOAD_DIR | tail -5
    fi
else
    echo "❌ 上传目录不存在"
fi

echo ""
echo "🔍 检查Nginx上传路径配置..."
curl -I http://localhost/uploads/ 2>/dev/null | head -1

echo ""
echo "📝 检查后端服务状态..."
pm2 show web-notes-api 2>/dev/null | grep -E "(status|restart time|cpu|memory)"

echo ""
echo "🔧 上传功能诊断完成！"
echo ""
echo "✅ 如果要手动测试:"
echo "1. 在浏览器中登录系统"
echo "2. 在笔记编辑器中点击 '插入图片' 按钮"
echo "3. 选择一个图片文件"
echo "4. 查看浏览器开发者工具的Network选项卡"
echo ""
echo "❌ 如果上传失败，请检查:"
echo "- 浏览器控制台错误"
echo "- PM2日志: pm2 logs web-notes-api"
echo "- Nginx错误日志: tail -f /var/log/nginx/web-notes-error.log"
echo "- 认证token是否有效"